package customerannotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class TestMyAnnotation {

    private String name; //null

    private void fn(String args) {

    }

    public String getName() {
        return name;
    }


    @MyAnnotation(value = "张三丰")
    public void setName(String name) {
        try {

            Class clazz = this.getClass();
            Method method = clazz.getDeclaredMethod("setName", String.class);
            //获取方法上的所有注解。
            Annotation[] annotations = method.getAnnotations();
            MyAnnotation currentAnnotation = null;

            boolean flag = false;
            for (Annotation anno : annotations) {
                //判断是否存在MyAnnotation注解。
                if (anno.annotationType() == MyAnnotation.class) {
                    currentAnnotation = (MyAnnotation) anno;
                    flag = true;
                    break;
                }
            }

            if (flag) {
                //如果存在MyAnnotation注解，this.name属性赋值为注解的value属性。
                String value = currentAnnotation.value();
                this.name = value;
            } else {
                this.name = name;//否则this.name赋值为参数name值。
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    public static void main(String[] args) {

        TestMyAnnotation t = new TestMyAnnotation();
        t.setName("张三");
        System.out.println(t.name);
    }
}
